#多进程锁,多线程锁都要实现一遍
#多进程通过Queue来实现进程通信#把上述概念熟记并理解

import time
from multiprocessing import Process, Lock
from threading import Thread, Lock
from multiprocessing import Process, Queue
#多进程锁
def save__file(index, Lock):
    with Lock:
        with open("第五周_第一节_作业.log", "a", encoding = "utf-8") as f:
            f.write(str(index) + "\n")

#多进程通过Queue来实现进程通信

def save_to_file(index, Lock):
    with Lock:
        with open("第五周_第一节_作业.log", "a", encoding = "utf-8") as f:
            f.write(str(index) + "\n")

def save_to_queue(index, my_queue):
    my_queue.put(index)

# 多线程锁

zero = 0
lock = Lock()

def foo():
    global zero
    for i in range(10 ** 6):
        with lock:
            zero += 1
            zero -= 1


if __name__ == "__main__":
    process_array = []
    lock = Lock()
    for i in range(10):
        p = Process(target = save_to_file, args = (i, lock))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()
    print("done!")

    process_array = []
    my_queue = Queue
    for i in range(10):
        p = Process(target=save_to_queue, args=(i, my_queue))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()
    while True:
        print(my_queue.get())


    thread_array = []
    for i in range(10):
        t = Thread(target=foo)
        process_array.append(t)
        t.start()
    for t in thread_array:
        t.join()
        print(zero)

